﻿using GMS.NET.Encrypt;
using GMS.NET.Web.Components.Shared.Global.Misc;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Net.Http.Headers;

namespace GMS.NET.Web.Components.Shared.Global.Attributes
{
    public class ApiSecurityAttribute : ApiFilterAttribute
    {
        private bool SetIdentity = true;

        /// <summary>
        ///  api接口的安全参数设定
        /// </summary>
        /// <param name="SetIdentity">是否设置身份信息,默认为true</param>
        public ApiSecurityAttribute(bool SetIdentity) => this.SetIdentity = SetIdentity;
        public ApiSecurityAttribute() { }
        public override async Task OnRequestAsync(ApiRequestContext context)
        {
            try
            {
                //获取系统密钥
                var app = context.HttpContext.ServiceProvider.GetService<IConfiguration>();
                var appkey = app!.GetSection(AppSetting.ServerKey).Value ?? "";
                //请求加密
                var timestamp = DateTimeOffset.Now.ToUnixTimeSeconds().ToString();
                var signature = API.GetSignature(timestamp, appkey);
                //放置请求头
                context.HttpContext.RequestMessage.Headers.Add(ApiHeaderConst.Timestamp, timestamp);
                context.HttpContext.RequestMessage.Headers.Add(ApiHeaderConst.Signature, signature);
                //设置身份认证
                if (SetIdentity)
                {
                    var AuthStateProvider = context.HttpContext.ServiceProvider.GetService<AuthenticationStateProvider>();
                    var AuthState = await AuthStateProvider!.GetAuthenticationStateAsync();
                    context.HttpContext.RequestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AuthState.User.AccessToken());
                }
            }
            catch (Exception) { }
        }

        public override Task OnResponseAsync(ApiResponseContext context)
        {
            if (SetIdentity)
            {
                var IsServerTag = context.HttpContext.ResponseMessage!.Headers
              .TryGetValues(ApiHeaderConst.ServiceValidationTag, out var serverTag);
                if (IsServerTag)
                {
                    if (serverTag!.FirstOrDefault() == ApiHeaderConst.Unauthorized401)
                    {
                        var Navigation = context.HttpContext.ServiceProvider.GetService<NavigationManager>();
                        Navigation!.NavigateTo("/auth");
                        throw new Exception("身份认证失败拒绝授权");
                    }
                    if (serverTag!.FirstOrDefault() == ApiHeaderConst.Forbidden403)
                        throw new Exception("拒绝授权访问该资源");
                }
            }
            return Task.CompletedTask;
        }
    }
}
